<?php
/**
 * 用户信息业务逻辑类
 * User: 苏近之
 * Date: 2019-03-23
 * Time: 18:50
 */

namespace app\user\service;

use app\user\exception\UserNotFound;
use app\user\model\PasswordHistory;
use app\user\model\User;
use think\Model;

class UserInfoService
{

    /**
     * 返回手机号是否已经注册
     * @param string $telephone 手机号
     * @throws
     * @return bool
     */
    public static function hasRegisterWithPhone($telephone): bool
    {
        $status = [User::STATUS_NORMAL, User::STATUS_BLOCK];
        $result = User::where(['telephone' => $telephone])
            ->whereIn('status', $status)->find();

        return boolval($result);
    }

    /**
     * 返回用户昵称是否已经存在
     * @param string $nickname 用户昵称
     * @return bool
     * @throws
     */
    public static function hasRegisterWithName(string $nickname): bool
    {
        $status = [User::STATUS_NORMAL, User::STATUS_BLOCK];
        $result = User::where(['nickname' => $nickname])
            ->whereIn('status', $status)->find();

        return boolval($result);
    }

    /**
     * 保存用户登录信息
     * @param string $nickname 用户昵称
     * @param string $telephone 手机号码
     * @param string $password 密码
     * @param string $email 邮箱
     * @return bool
     */
    public static function saveUserLoginInfo($nickname, $telephone, $password, $email = ''): bool
    {
        $userModel = new User;
        $password = password_hash($password, PASSWORD_DEFAULT);
        $result = $userModel->insert(compact('nickname', 'telephone', 'password', 'email'));
        // 记录历史密码
        (new PasswordHistory)->insert([
            'user_id' => $userModel->getLastInsID(),
            'password_hash' => $password,
        ]);

        return boolval($result);
    }

    /**
     * 返回用户登录信息
     * @param string $account 账户
     * @throws
     * @return array|\PDOStatement|string|Model
     */
    public static function getUserLoginInfo(string $account)
    {
        $user = User::where('nickname|telephone|email', '=', $account)->find();
        if (is_null($user)) {
            throw new UserNotFound();
        }

        return $user;
    }
}